﻿using System;
using System.Linq;
using System.Web.UI;
using Medianamik.Core;
using Telerik.Web.UI;

namespace Medianamik.UI.ConfigManagement.UserControls
{
    public partial class PageList : BaseModuleListUserControl
    {
        protected override RadGrid Grid
        {
            get { return GridPages; }
        }

        protected override UpdatePanel GridUpdatePanel
        {
            get { return mainUpdatePanel; }
        }

        protected override string ManagementURL
        {
            get { return "PageManagement.aspx"; }
        }

        protected override void GridNeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            GridPages.DataSource = ConfigManager.GetAll<MedianamikPageDisplay>(Page.CurrentUICulture)
                .OrderBy(m => m.Position);
        }

        private void CollapseAll()
        {
            foreach (GridItem item in GridPages.MasterTableView.Controls[0].Controls)
            {
                if (item is GridGroupHeaderItem)
                {
                    item.Expanded = false;
                }
            }
        }

        protected void GridPages_RowDrop(object sender, GridDragDropEventArgs e)
        {
            if (e.DraggedItems[0].OwnerGridID == GridPages.ClientID)
            {
                //Réordonner un noeud
                Guid destinationNodeId;
                var movedNode = NodeManager.GetNode((Guid) e.DraggedItems[0].GetDataKeyValue("ID"));
                destinationNodeId = (Guid) e.DestDataItem.GetDataKeyValue("ID");

                var pos = e.DropPosition == GridItemDropPosition.Above
                              ? DropPosition.Above
                              : DropPosition.Below;

                NodeManager.ChangeNodeOrder(movedNode, destinationNodeId, pos);
                GridPages.Rebind();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            var script =
                @"
                function onRowDropping(sender, args) {{
                    
                }}";

            ScriptManager.RegisterClientScriptBlock(this, GetType(),
                                                    "onRowDropping", string.Format(script, Grid.ClientID), true);
        }

        private class MedianamikPageDisplay : MedianamikPage
        {
            public string MenuName
            {
                get
                {
                    var menu = GetMenuGroup();
                    return menu == null ? "&nbsp;" : menu.Name;
                }
            }

            public string ModuleName
            {
                get
                {
                    var module = Module;
                    return module == null ? "&nbsp;" : module.Name;
                }
            }
        }
    }
}